<template>
  <div class="role_list">
    <a-card>
      <!-- 创建按钮 -->
      <div class="role_title">
        <span>角色列表</span>
        <a-button type="primary" class="set_up" icon="plus" @click="onSetUpRole" v-action:add="'role'">新建</a-button>
      </div>
      <!-- 表格 -->
      <a-table 
        :columns="columns" 
        :data-source="roleList" 
        :pagination="currentConfig"
        :loading="table_loading"
        @change="onTableHandle"
        :scroll="{x: true}"
        rowKey="id"
        style="margin-top:24px;"
      >
        <span slot="action" slot-scope="row">
          <a @click="onUpdateRole(row)" v-action:edit="'role'">编辑</a>
          <a-divider type="vertical" style="opacity: 0;" />
          <a @click="onDeleteRole(row)" v-action:delete="'role'">删除</a>
        </span>
      </a-table>
    </a-card>
    <!-- 抽屉 -->
    <a-modal
      :title="title"
      :visible="visible"
      :confirm-loading="form.loadingBtn"
      :maskClosable="false"
      @ok="onSubmit"
      @cancel="onClose"
    >
      <!-- 表单 -->
      <a-form-model
        ref="ruleForm"
        :model="form.data"
        :rules="rules"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 20 }"
      >
        <!-- 角色名称 -->
        <a-form-model-item label="角色名称" prop="name">
          <a-input v-model="form.data.name" placeholder="请输入角色名称" :disabled="!!form.data.id" />
        </a-form-model-item>
        <!-- 显示名称 -->
        <a-form-model-item label="显示名称" prop="displayName">
          <a-input v-model="form.data.displayName" placeholder="请输入显示名称"/>
        </a-form-model-item>
        <!-- 角色说明 -->
        <a-form-model-item label="角色说明" prop="remark">
          <a-input v-model="form.data.remark" type="textarea" placeholder="请输入角色说明" />
        </a-form-model-item>
        <!-- 角色权限 -->
        <a-form-model-item label="权限" prop="permissionIds">
          <a-tree-select
            v-model="form.data.permissionIds"
            placeholder="请选择权限"
            allow-clear
            multiple
            @select="onTreeSelect"
            tree-checkable
            :showCheckedStrategy="SHOW_PARENT"
          >
            <a-tree-select-node v-for="item in treedPermissions" :key="item.key" :value="item.value" :title="item.title">
              <template v-if="item.children&&item.children.length">
                <a-tree-select-node v-for="node in item.children" :key="node.key" :value="node.value" :title="node.title">
                </a-tree-select-node>
              </template>
            </a-tree-select-node>
          </a-tree-select>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import { mapActions, mapMutations, mapState } from 'vuex'
import { TreeSelect } from 'ant-design-vue';
import { baseMixin } from '@/store/app-mixin';
const SHOW_PARENT = TreeSelect.SHOW_PARENT;
const columns = [
        { 
          title: '角色id', 
          dataIndex: 'id', 
          sorter: true
        },
        { 
          title: '角色名称', 
          dataIndex: 'name', 
          sorter: true
        },
        { 
          title: '显示名', 
          dataIndex: 'displayName', 
          sorter: true
        },
        { 
          title: '说明', 
          dataIndex: 'remark' 
        },
        { 
          title: '创建时间', 
          dataIndex: 'createdAt', 
          sorter: true
        },
        { 
          title: '更新时间', 
          dataIndex: 'updatedAt', 
          sorter: true
        },
        {
          title: '操作',
          fixed: 'right',
          width: 100,
          scopedSlots: { customRender: 'action' }
        }
      ]

  export default {
    name: 'RoleList',
    mixins: [baseMixin],
    data () {
      return {
        columns,
        visible: false,
        title: '创建角色',
        table_loading: false,
        form: {
          statusBtn: false,
          loadingBtn: false,
          data: {
            permissionIds: []
          }
        },
        SHOW_PARENT,
        rules: {
          name: [
            { 
              required: true, 
              trigger: 'blur',
              message: '请输入角色名' 
            },
            { 
              max: 50,
              trigger: 'blur',
              message: '最大限制长度为50个字符' 
            }
          ],
          displayName: [
            { 
              required: true, 
              trigger: 'blur',
              message: '请输入显示名称' 
            },
            { 
              max: 100,
              trigger: 'blur',
              message: '最大限制长度为100个字符' 
            }
          ],
          remark: [
            { 
              max: 255, 
              trigger: 'blur',
              message: '最大长度不能超过255个字符' 
            }
          ],
          permissionIds: [
            {
              type: 'array', 
              required: true, 
              trigger: 'change',
              message: '最少选择一项权限'
            }
          ]
        },
        autoExpandParent: true,
        selectedKeys: [],
      }
    },
    watch: {
      // 关闭抽屉清空表单
      visible (val) {
        if (!val) {
          this.form.data = { permissionIds: [] }
          this.$refs.ruleForm && this.$refs.ruleForm.clearValidate()
        }
      }
    },
    computed: {
      ...mapState('roleManage',['roleList', 'permissionList', 'currentConfig']),
      treedPermissions () {
        return this.generateTree(this.permissionList)
      },
    },
    mounted () {
      this.onLoadRoleConfig()
    },
    methods: {
      ...mapMutations('roleManage', ['SET_CURRENT', 'SET_PAGE', 'SET_ORDER']),
      ...mapActions('roleManage', ['getAllRoleList', 'addRoleList', 'updateRole', 'getUpdateList', 'deleteRoleList', 'getPermissionList']),
      // 保存
      onSubmit () {
        this.$refs.ruleForm.validate(valid => {
          if (valid) {
            this.form.statusBtn = true
            this.form.loadingBtn = true
            if (this.form.data.id) {
              this.updateRole({...this.form.data})
                .then((res) =>  {
                  this.visible = false
                  this.$message.success('角色修改成功')
                  this.getAllRoleList()
                })
                .catch(err => this.$message.error('创建角色失败，原因：' + err.msg + '！'))
                .finally(() => {
                  this.form.loadingBtn = false
                  this.form.statusBtn = false
                })
            }else {
              this.addRoleList({ ...this.form.data })
                .then((res) =>  {
                  this.visible = false
                  this.$message.success('角色创建成功')
                  this.getAllRoleList()
                })
                .catch(err => this.$message.error('创建角色失败，原因：' + err.msg + '！'))
                .finally(() => {
                  this.form.loadingBtn = false
                  this.form.statusBtn = false
                })
            }
          } else {
            setTimeout(()=>{
              this.form.loadingBtn = false
              this.form.statusBtn = false
              return false
            }, 1500)
          }
        })
      },
      onTreeSelect () {},
      // 创建
      onSetUpRole () {
        this.visible = true
        this.title = '创建角色'
      },
      // 关闭抽屉
      onClose () {
        this.visible = false
        // this.$confirm({
        //   title: '提示',
        //   content: '关闭后数据会丢失，确定关闭吗？',
        //   okText: '确定',
        //   cancelText: '取消',
        //   onOk: () => {
        //     this.visible = false
        //   },
        //   onCancel: () => {},
        // })
      },
      order_way (order) {
        if (order == 'ascend') {
          return 'asc'
        } else if(order == 'descend') {
          return 'desc'
        } else {
          return ''
        }
      },
      // 分页-每页条数
      onTableHandle (page, filters, {field, order}) {
        const orderObj = {
          order: this.order_way(order),
          orderBy: field || ''
        }
        this.SET_CURRENT(page.current)
        this.SET_PAGE(page.pageSize)
        this.SET_ORDER({...orderObj})
        this.getAllRoleList()
      },
      // 获取修改行
      onUpdateRole (row) {
        this.title='修改角色'
        this.visible = true
        this.getUpdateList(row.id)
          .then((res) => {
            this.form.data = {...res.data}
          })
          .catch((err) => this.$message.error('获取修改角色信息失败，原因：' + err.msg + '！'))
      },
      // 获取删除行
      onDeleteRole (row) {
        this.$confirm({
          title: '删除提示',
          content: '删除角色信息无法恢复，您确定要继续吗？',
          okText: '确定',
          cancelText: '取消',
          onOk: () => {
            this.deleteRoleList(row.id)
            .then(()=>{
              this.$message.success('角色删除成功')
              this.getAllRoleList()
            })
            .catch((err) => this.$message.error('角色删除失败，原因：' + err.msg + '！'))
          },
          onCancel: () => {},
        })
      },
      // 初始化加载页面数据
      onLoadRoleConfig () {
        this.table_loading = true;
        this.getAllRoleList()
          .then(res =>{})
          .catch(err =>{
            if (err.code == 401) {
              this.err401(err)
              return
            }
            this.$message.error('获取角色列表失败，原因：' + err.msg + '！')
          })
          .finally(res =>{
            this.table_loading = false;
          })
        this.getPermissionList()
          .then(res =>{})
          .catch(err =>{
            this.$message.error('获取权限列表失败，原因：' + err.msg + '！')
          }) 
      },
      generateTree (data) {
        const nodeMap = {}
        const nodes = []
        data.forEach((item, index) => {
          const node = {}
          node.title = item.displayName
          node.key = item.id
          node.value = item.id
          if (item.parent && item.parent != 0) {
            node.parent = item.parent
          }
          nodeMap[item.id] = node
          nodes.push(node)
        })
        const treeData = nodes.filter(node=>{
          if (!node.parent) {
            return node
          }
        })
        const treeNodes = nodes.filter(node=>{
          if (node.parent) {
            return node
          }
        })
        for (let j=0; j<treeData.length; j++){
          treeData[j].children = []
          for (let i=0; i<treeNodes.length; i++) {
            if (treeData[j].key == treeNodes[i].parent) {
              treeData[j].children.push(treeNodes[i])
            }
          }
        }
        return treeData
      },
    }
  }
</script>

<style scoped>
.role_list{
  width: 100%;
  height: 100%;
}
.set_up{
  float: right;
}

.ant-drawer>>>.ant-drawer-body{
  height: calc(100% - 55px);
}

.ant-form{
  height: 100%;
  display: flex;
  flex-direction: column;
}

.submit_style{
  margin-bottom: 0;
  flex: 1;
}

.submit_style>>>.ant-col.ant-col-18.ant-form-item-control-wrapper{
  width: 100%;
  height: 100%;
}

.submit_style>>>.ant-form-item-control{
  display: flex;
  height: 100%;
  align-items: flex-end;
}

.submit_style>>>span.ant-form-item-children{
  width: 100%;
}

.save_button,
.cancal_button {
  float: right;
}

.cancal_button {
  margin-right: 15px;
}

.role_title{
  display: flex;
  justify-content: space-between;
}


.role_title span {
  display: block;
  float: left;
  margin-bottom: 0;
  padding-right: 12px;
  color: rgba(0,0,0,.85);
  font-weight: 500;
  font-size: 16px;
  line-height: 32px;
}

.ant-table-wrapper>>>td.ant-table-row-cell-break-word {
  padding: 10px;
}

.role_list>>>.ant-table-pagination.ant-pagination {
  width: 100%;
  display: flex;
}

.role_list>>>.ant-table-pagination.ant-pagination >li:not(:first-child) {
  float: right;
}

.role_list>>>.ant-table-pagination.ant-pagination >li:first-child {
  font-size: 15px;
  color: #999;
  text-indent: 10px;
  flex: 1;
}

</style>